/**
 * 
 */
package it.unitn.testbed.server.config;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.apache.log4j.Logger;

/**
 * A servlet to download the configuration file.
 * 
 * @author Stefan Guna
 * 
 */
public class ConfigDownload extends HttpServlet {
	public static Logger log = Logger.getLogger(ConfigDownload.class.getName());
	private static final long serialVersionUID = 1L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			returnConfig(resp);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

	/**
	 * @param resp
	 * @throws IOException
	 * @throws ParserConfigurationException
	 * @throws TransformerException
	 */
	private void returnConfig(HttpServletResponse resp) throws IOException,
			ParserConfigurationException, TransformerException {
		ConfigUser configUser = TestbedConfig
				.getConfigurationUsers().get(0);
		TestbedConfig config = configUser.getConfig();
		resp.setContentType("application/x-download");
		resp.setHeader("Content-Disposition",
				"attachment; filename=testbed.xml");
		OutputStream out = resp.getOutputStream();
		config.dumpConfigXml(out);
	}

}
